package com.hzit.servlet;

import com.alibaba.fastjson.JSON;
import com.hzit.entity.Student;
import com.hzit.service.StudentService;
import com.hzit.service.impl.StudentServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
	private StudentService studentService;
	// 1. 初始化进调用一次
	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		studentService = new StudentServiceImpl();
	}
	// 2. 每次请求都会调用
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//2.0 处理中文乱码（post请求）
		req.setCharacterEncoding("UTF-8");
		//2.1 设置响应类型
		resp.setContentType("text/html;charset=utf8");
		//2.1 查询出所有学生列表
		List<Student> students = studentService.findAll();
		//2.2 将学生集合转化为字符串
		String s = JSON.toJSONString(students);
		//2.3 将字符串数据响应到页面
		resp.getWriter().println(s);
		resp.getWriter().flush();
	}

	// @Override
	// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// 	System.out.println("doGet...");
	// }

	// @Override
	// protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// 	doGet(req,resp);
	// }
	@Override
	public String getServletInfo() {
		return null;
	}
	// servlet销毁时执行一次
	@Override
	public void destroy() {
		System.out.println("destroy...");
	}

}
